import moment from 'moment-timezone';
import type { IProps } from '@/components/CustomElement/DateFormatter/interface';
import type { Moment, MomentInput } from 'moment';

/**
 * 将UTC时间转换为本地或指定时区的时间
 * @param utcDate
 * @param opt
 */
export const toLocalDate = (utcDate?: MomentInput, opt: { timezone?: string } = {}): Moment => {
    const d = moment.utc(utcDate);
    const { timezone = 'Asia/Shanghai' } = opt;
    if (timezone) {
        d.tz(timezone);
    }
    return d;
};

/**
 * 返回UTC 0 时间
 * @param localDate
 * @param opt
 */
export const toUTCDate = (
    localDate?: MomentInput | string,
    opt: {
        formatStr?: string;
        timezone?: string;
        returnString?: boolean;
    } = {
        formatStr: 'YYYY-MM-DD HH:mm:ss',
        timezone: 'Asia/Shanghai',
        returnString: true,
    },
): string | Moment => {
    if (opt.returnString) {
        // @ts-ignore
        return moment.tz(localDate, opt.timezone).utc().format(opt.formatStr);
    }
    // @ts-ignore
    return moment.tz(localDate, opt.timezone).utc();
};

/**
 * 将时间格式化成string
 * @param data
 */
export const format = (data: IProps) => {
    const {
        date, // 时间
        formatStr = 'YYYY-MM-DD HH:mm:ss', // 时间格式化样式
        formatStrDate = 'YYYY-MM-DD', // 日期格式化
        showTime = true, // 是否只显示时分秒
        showDate = true,
        isUTC = true, // 是否转UTC 0
        radix = 24, // 时区进制
        timezone = 'Asia/Shanghai', // 时区
    } = data;
    const d = isUTC ? toLocalDate(date) : date;
    if (showTime) {
        if (timezone) {
            return moment(d)
                .tz(timezone)
                .format(radix == 24 ? 'HH:mm:ss' : 'hh:mm:ss');
        }
        return moment(d).format(radix == 24 ? 'HH:mm:ss' : 'hh:mm:ss');
    }
    if (showDate) {
        return moment(d).format(formatStrDate);
    }
    return timezone ? moment(d).tz(timezone).format(formatStr) : moment(d).format(formatStr);
};

const DateFormat = (props: IProps) => {
    const { date, emptyContent, ...rest } = props;
    return <div>{date ? DateFormat.format({ date: date, ...rest }) : emptyContent}</div>;
};

DateFormat.format = format;
DateFormat.toLocalDate = toLocalDate;

export default DateFormat;
